/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 26727
 * Date: 2024-11-04
 * Time: 23:34
 */
class Solution10 {
    // 归并排序法
    public ListNode sortList(ListNode head) {
        // 特殊判断
        if(head == null || head.next == null) {
            return head;
        }
        // 快慢指针找到中间节点
        ListNode fast = head.next;
        ListNode slow = head;

        while(fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        // 找到中间节点
        ListNode mid = slow.next;
        slow.next = null;

        ListNode left = sortList(head);
        ListNode right = sortList(mid);

        return merge(left,right);
    }

    public ListNode merge(ListNode left,ListNode right) {
        ListNode newHead = new ListNode();
        ListNode cur = newHead;

        while(left != null && right != null) {
            if(left.val < right.val) {
                cur.next = left;
                left = left.next;
            }else {
                cur.next = right;
                right = right.next;
            }
            cur = cur.next;
        }
        // 剩余连接
        cur.next = left != null ? left : right;
        return newHead.next;
    }
}
